package com.itstyle.quartz.test;

import okhttp3.*;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class DeepSeekClient {
    private static final String API_URL = "https://api.deepseek.com/chat/completions";
    private final String apiKey;
    private OkHttpClient client;

    public DeepSeekClient(String apiKey) {
        this.apiKey = apiKey;
        this.client = new OkHttpClient.Builder()
                .connectTimeout(30, TimeUnit.SECONDS)  // 连接超时
                .readTimeout(120, TimeUnit.SECONDS)     // 读取超时
                .writeTimeout(30, TimeUnit.SECONDS)    // 写入超时
                .build();
    }

    public String generateResponse(String prompt) throws IOException {
        MediaType JSON = MediaType.get("application/json; charset=utf-8");
        String jsonBody = "{" +
                "\"model\": \"deepseek-chat\"," +
                "\"messages\": [" +
                "{" +
                "\"role\": \"user\"," +
                "\"content\": \"" + escapeJson(prompt) + "\"" +
                "}" +
                "]," +
                "\"temperature\": 1" +
                "}";

        RequestBody body = RequestBody.create(jsonBody, JSON);
        Request request = new Request.Builder()
                .url(API_URL)
                .header("Content-Type", "application/json")
                .header("Authorization", "Bearer " + apiKey)
                .post(body)
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (response.code() == 402) {
                System.err.println("API请求被拒绝：需要付费订阅");
                System.err.println("请检查你的API密钥是否已关联有效付费计划");
                return null;
            }
            if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
            assert response.body() != null;
            return response.body().string();
        }
    }

    private String escapeJson(String input) {
        if (input == null) {
            return "";
        }
        return input.replace("\\", "\\\\")
                .replace("\"", "\\\"")
                .replace("\b", "\\b")
                .replace("\f", "\\f")
                .replace("\n", "\\n")
                .replace("\r", "\\r")
                .replace("\t", "\\t");
    }

    public static void main(String[] args) throws IOException {

        String apiKey = "sk-5e139c005cf8467882e9b1ccfbf482cc"; // 替换为你的实际API密钥
        DeepSeekClient client = new DeepSeekClient(apiKey);
        String prompt = "女人的生理期需要注意什么";

        try {
            String response = client.generateResponse(prompt);
            System.out.println("API响应: " + response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void ask() throws IOException {
        String apiKey = "sk-5e139c005cf8467882e9b1ccfbf482cc";
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, "{\n  \"messages\": [\n    {\n      \"content\": \"You are a helpful assistant\",\n      \"role\": \"system\"\n    },\n    {\n      \"content\": \"简述下java的用法\",\n      \"role\": \"user\"\n    }\n  ],\n  \"model\": \"deepseek-chat\",\n  \"frequency_penalty\": 0,\n  \"max_tokens\": 2048,\n  \"presence_penalty\": 0,\n  \"response_format\": {\n    \"type\": \"text\"\n  },\n  \"stop\": null,\n  \"stream\": false,\n  \"stream_options\": null,\n  \"temperature\": 1,\n  \"top_p\": 1,\n  \"tools\": null,\n  \"tool_choice\": \"none\",\n  \"logprobs\": false,\n  \"top_logprobs\": null\n}");
        Request request = new Request.Builder()
                .url("https://api.deepseek.com/chat/completions")
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .addHeader("Authorization", "Bearer "+apiKey)
                .build();
        Response response = client.newCall(request).execute();
        System.out.println(response.body().string());
    }
}
